<?php
class Application_Plugin_Acl extends Zend_Controller_Plugin_Abstract{
	private $_noauth = array(
		'module'		=> 'default',
		'controller'	=> 'login',
		'action'		=> 'index'
	);
	
	private $_noacl = array(
		'module'		=> 'default',
		'controller'	=> 'error',
		'action'		=> 'deny'
	);
	
	public function preDispatch(Zend_Controller_Request_Abstract $request){
		$acl = null;
		$role = null;
		
		if(Zend_Registry::isRegistered('DefaultAcl')){
			$acl = Zend_Registry::get('DefaultAcl');
		} else {
			throw new Zend_Controller_Exception("Acl not defined !");
		}
		
		$auth = Zend_Auth::getInstance();
		
		if($auth->hasIdentity()){
			$role = $auth->getIdentity()->role;
		} else {
			$role = 'guest';
		}
		$module = $request->getModuleName();
		$controller = $request->getControllerName();
		$action = $request->getActionName();
		
		$ressource = $module.':'.$controller;
				
		if(!$acl->has($ressource)){
			$ressource = null;
		}
		
		if(!$acl->isAllowed($role,$ressource,$action)){
			if(!$auth->hasIdentity()){
				$module = $this->_noauth['module'];
				$controller = $this->_noauth['controller'];
				$action = $this->_noauth['action'];
			} else {
				$module = $this->_noacl['module'];
				$controller = $this->_noacl['controller'];
				$action = $this->_noacl['action'];
			}
		}
		
		$request->setModuleName($module);
		$request->setControllerName($controller);
		$request->setActionName($action);
	}
}